import Cache from "../../cache/index.js"
import defaultConfig from "../config.js"

const dictMap = 'ingrun_dict_data'
function formatDict(labelKey = 'label', valueKey = 'value', list) {
  return list.map(i => {
    return {
      label: i[labelKey],
      value: i[valueKey],
      data: i
    }
  })
}

export default class IRDict {

  constructor(vue, config = defaultConfig) {
    this._vue = vue
    this._config = config
    this._cache = Cache.create(this._vue)
    this._cache.set(dictMap, {})
  }

  addDictItme = (dictKey, dictList) => {
    const config = this._config
    this._vue.set(this._cache.get(dictMap), dictKey, formatDict(config.labelKey, config.valueKey, dictList))
  }

  getDictList = (dictKey) => {
    const list = this._cache.get(dictMap)[dictKey]
    if (!list) {
      this.addDictItme(dictKey, [])
      const config = this._config
      config.remoteMethod && config.remoteMethod(dictKey, this.addDictItme)
      return this.getDictList(dictKey)
    }
    return list
  }

  getDictLabel = (dictKey, dictValue) => {
    const list = this.getDictList(dictKey)
    const item = list.find(i => i.value == dictValue)
    if (item) {
      return item.label
    }
    return '-'
  }
}
